import React, { Component } from 'react';
import _ from 'lodash';
import * as API from '@api/auth';
import { message } from 'antd';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { withRouter } from 'react-router-dom';
import { actions as authActions } from '@redux/reducer/auth';

// 通过证书控制页面卓望单点登录功能是否启用
function isSsologinOpen(cert) {
  const contents = cert.custom_content?.split(',') || [];
  return contents.indexOf('NSMP-SSO=1') !== -1 ? true : false;
}

class LandingPage extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { cert } = this.props;

    if (isSsologinOpen(cert)) {
      this.ssoLoginZhuowang();
    }
  }

  // 卓望-单点登录功能
  ssoLoginZhuowang() {
    const { setAuth, history } = this.props;
    const onLoginSuccess = res => {
      const user = _.get(res, 'data.data');
      const token = _.get(res, 'data.data.token');
      const nsmpLoginPath = _.get(res, 'data.data.nsmpLoginPath');
      // nsmpLoginPath存于浏览器缓存
      localStorage.setItem('nsmpLoginPath', nsmpLoginPath);
      user.nickname = user.role;
      setAuth({ user, token });
      if (user.role === '审计员') {
        history.push('/log-manage/login-log');
      } else if (user.role === '系统管理员') {
        history.push('/asset-config/organization');
      } else {
        history.push('/');
      }

      message.success('登录成功');
    };
    const onLoginFail = err => {
      message.error(err.message || 'sign校验失败');
      setTimeout(() => {
        window.location.href = localStorage.getItem('nsmpLoginPath');
      }, 1000);
    };

    const sign = new URLSearchParams(window.location.search).get('sign');

    API.loginFromNSMP({ sign })
      .then(onLoginSuccess)
      .catch(onLoginFail);
  }

  render() {
    return <span style={{ display: false }}>通用免登录中间页</span>;
  }
}

LandingPage.propTypes = {
  setAuth: PropTypes.func,
  history: PropTypes.object,
  cert: PropTypes.object
};

const mapStateToProps = state => {
  return {
    cert: _.get(state, 'auth.cert', {})
  };
};

const mapDispatchToProps = dispatch => {
  return {
    ...bindActionCreators(authActions, dispatch)
  };
};

export default withRouter(
  connect(
    mapStateToProps,
    mapDispatchToProps
  )(LandingPage)
);
